package chapter_3.frame;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class TestFramer {

    private static final String[] messages = {"Hello World!", "Hello China, 你好 中国", "世界人民大团结万岁",
            "在消息中发送分隔符\n和替换符}的情况"};

    public static void main(String[] args) throws InterruptedException {
        Thread clientThread = new Thread(() -> {
            Socket socket = null;
            try {
                socket = new Socket(InetAddress.getLocalHost(), 8888);
                InputStream in = socket.getInputStream();
                OutputStream out = socket.getOutputStream();
                //Framer framer = new DelimitFramer(in);
                DataInputStream dataInputStream = new DataInputStream(in);
                Framer framer = new LengthFramer(dataInputStream);
                for (String msg : messages) {
                    byte[] msgBytes = msg.getBytes(StandardCharsets.UTF_8);
                    framer.frameMsg(msgBytes, out);
                    System.out.println(Thread.currentThread().getName() + " 发送消息: " + msg);
                }
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        Thread serverThread = new Thread(() -> {
            Socket socket = null;
            try (ServerSocket serverSocket = new ServerSocket(8888)) {
                while (true) {
                    socket = serverSocket.accept();
                    System.out.println("获取到来自" + socket.getRemoteSocketAddress() + "的tcp连接");
                    InputStream in = socket.getInputStream();
                    OutputStream out = socket.getOutputStream();
                    //Framer framer = new DelimitFramer(in);
                    DataInputStream dataInputStream = new DataInputStream(in);
                    Framer framer = new LengthFramer(dataInputStream);
                    byte[] recvMsgBytes = null;
                    do {
                        recvMsgBytes = framer.nextMsg();
                        //System.out.println(Arrays.toString(recvMsgBytes));
                        if (recvMsgBytes != null) {
                            System.out.println(Thread.currentThread().getName() + " 接收到的消息: " + new String(recvMsgBytes, StandardCharsets.UTF_8));
                        }
                    } while (recvMsgBytes != null);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        serverThread.setName("server");
        clientThread.setName("client");
        serverThread.start();
        Thread.sleep(3000);
        clientThread.start();
    }
}
